<template>
    <ElTable :data="tableData" class="my-table">
        <ElTableColumn label="用户ID" width="180" prop="id"></ElTableColumn>
        <ElTableColumn label="用户头像" width="100" prop="roleList">
            <template #default="{ row }">
                <div class="avatar-box flex">
                    <img v-if="row.avatar" :src="row.avatar" class="img-avatar" />
                    <ElIcon v-else size="32"><MyIcon name="avatar"></MyIcon></ElIcon>
                </div>
            </template>
        </ElTableColumn>
        <ElTableColumn label="账号" width="160" prop="account"></ElTableColumn>
        <ElTableColumn label="昵称" width="160" prop="name"></ElTableColumn>
        <ElTableColumn label="手机号" width="160" prop="phone"></ElTableColumn>
        <ElTableColumn label="邮箱" width="240" prop="email"></ElTableColumn>
        <ElTableColumn label="用户角色" prop="roleList">
            <template #default="{ row }">
                {{ getRoleStr(row.roleList) }}
            </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="注册时间" prop="createTime" width="170"></ElTableColumn> -->
        <ElTableColumn label="操作" width="280">
            <template #default="{ row }">
                <ElButton v-if="!isSuperAdmin(row)" type="danger" link @click="deleteRow(row.id)">删除</ElButton>
                <ElButton v-if="!isSuperAdmin(row)" type="primary" link @click="assignRoles(row)">分配角色</ElButton>
                <ElButton v-if="!isSuperAdmin(row)" type="primary" link @click="resetRow(row.id)">重置密码</ElButton>
            </template>
        </ElTableColumn>
    </ElTable>
    <ResetPasswordDialog ref="resetPasswordDialog"></ResetPasswordDialog>
    <AssignRolesDialog ref="assignRolesDialog" @complete="assignComplete"></AssignRolesDialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from 'element-plus';
import ResetPasswordDialog from './ResetPasswordDialog.vue';
import AssignRolesDialog from './AssignRolesDialog.vue';

interface Params {
    searchKey: string;
    current: number;
    size: number;
}

const tableData = ref<any[]>([]);

const params = ref<Params>({
    searchKey: '',
    current: 1,
    size: 10,
});

const isSuperAdmin = (row: any): boolean => {
    return row?.account === 'superAdmin';
};

const getRoleStr = (roleList: any[]): string => {
    let str = '';
    if (Array.isArray(roleList)) {
        str = roleList.map((item) => item?.name || '').join(' | ');
    }
    return str;
};

const getData = async (data?: Partial<Params>): Promise<number> => {
    if (data) {
        params.value = { ...params.value, ...data };
    }
    const res = await MyService.account.getUserList(params.value);
    if (res.code === 200) {
        tableData.value = res.data.records;
        return res.data.total;
    } else {
        return 0;
    }
};

const deleteRow = async (userId: string) => {
    try {
        await ElMessageBox.confirm('是否确认删除改用户？', '操作提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const res = await MyService.account.deleteUser([userId]);
        if (res.code === 200) {
            getData({ current: 1 });
        } else {
            ElMessage.error({ message: res.msg || '用户删除失败' });
        }
    } catch (error) {}
};

const resetPasswordDialog = ref();
const assignRolesDialog = ref();

const resetRow = async (userId: string) => {
    resetPasswordDialog.value?.open(userId);
};

const assignRoles = async (row: any) => {
    assignRolesDialog.value?.open(
        row.id,
        row.roleList.filter((item: any) => !!item).map((item: any) => item?.id || '')
    );
};

const assignComplete = () => {
    getData();
};

defineExpose({
    refresh: getData,
});
</script>

<style scoped>
.img-avatar {
    height: 32px;
    width: 32px;
    border-radius: 16px;
    object-fit: contain;
}
</style>
